package models

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	util2 "zhanyan/pac/util"
)

var db *gorm.DB

//var logR, _ = util2.GetLogger(util2.Running)
var logE, _ = util2.GetLogger(util2.Errors)

// DbInitial 初始化数据库
func DbInitial() {
	var err error
	db, err = gorm.Open(util2.DatabaseSetting.Type, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
		util2.DatabaseSetting.User,
		util2.DatabaseSetting.Password,
		util2.DatabaseSetting.Host,
		util2.DatabaseSetting.Name))

	if err != nil {
		logE.Info("数据库链接失败 err: %v", err)
	}

	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return util2.DatabaseSetting.TablePrefix + defaultTableName
	}

	db.SingularTable(true)
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)
	db.AutoMigrate(&Teacher{}, &Student{}, &Seat{}, &Classroom{})
}

func GetDb() *gorm.DB {
	return db
}

func CloseDb() error {
	return db.Close()
}
